package net.ibizsys.eclipse.studio.api;

import java.util.HashMap;
import java.util.Map;

import net.ibizsys.eclipse.studio.Activator;
import net.ibizsys.eclipse.studio.i18n.I18n;
import net.ibizsys.eclipse.studio.util.HTTPKit;

/**
 * 服务器API管理对象
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public class APIManager
{
	/**
	 * 登录
	 */
	public static final String ACTION_LOGIN = "LOGIN";

	/**
	 * 查找解决方案
	 */
	public static final String ACTION_LISTDEVSLN = "LISTDEVSLN";

	/**
	 * 查找解决方案系统
	 */
	public static final String ACTION_LISTDEVSLNSYS = "LISTDEVSLNSYS";

	/**
	 * 登录
	 * 
	 * @param clazz 数据类型
	 * @param url 远程地址
	 * @param username 用户名
	 * @param password 密码
	 * @return 结果
	 * @throws Exception
	 */
	public static <T> ActionResult<T> login(Class<T> clazz, String url, String username, String password)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put("srfaction", ACTION_LOGIN);
		params.put("loginname", username);
		params.put("pwd", password);

		CallResult callResult = HTTPKit.post(url, params);

		return wrapResult(clazz, callResult);
	}

	/**
	 * 注销
	 */
	public static void logout()
	{

	}

	/**
	 * 查找全部解决方案
	 * 
	 * @param clazz 数据类型
	 * @return
	 */
	public static <T> ActionResult<T> findSolutions(Class<T> clazz)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put("srfaction", ACTION_LISTDEVSLN);
		params.put("srfloginkey", Activator.getDefault().curUser().getToken());

		CallResult callResult = HTTPKit.post(Activator.getDefault().curUser().getRemoteUrl(), params);

		return wrapResult(clazz, callResult);
	}

	/**
	 * 查找解决方案下系统
	 * 
	 * @param clazz 数据类型
	 * @param psdevslnid 解决方案标识
	 * @return
	 */
	public static <T> ActionResult<T> findSystems(Class<T> clazz, String psdevslnid)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put("srfaction", ACTION_LISTDEVSLNSYS);
		params.put("srfloginkey", Activator.getDefault().curUser().getToken());
		params.put("psdevslnid", psdevslnid);

		CallResult callResult = HTTPKit.post(Activator.getDefault().curUser().getRemoteUrl(), params);

		return wrapResult(clazz, callResult);
	}

	/**
	 * 包装转换返回结果
	 * 
	 * @param clazz
	 * @param callResult
	 * @return
	 */
	private static <T> ActionResult<T> wrapResult(Class<T> clazz, CallResult callResult)
	{
		if (callResult.isOK())
		{
			if (callResult.getContent() != null)
			{
				return new ActionResult<T>(clazz, callResult.getContent());
			} else
			{
				callResult.setRetcode(-1);
				callResult.setErrorInfo(I18n.HttpNullDataError);
			}
		}

		return new ActionResult<T>(callResult.getRetcode(), callResult.getErrorInfo());
	}
}
